package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.web.admin.mapper.SystemUserMapper;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private SystemUserMapper systemUserMapper;


    @Override
    public CaptchaVo getCode() {
        //创建SpecCaptcha对象
        SpecCaptcha specCaptcha = new SpecCaptcha(150, 50, 4);
        //获取验证码
        String code = specCaptcha.text();
        //获取验证码的图片地址
        String imageUrl = specCaptcha.toBase64();
        //使用UUID生成一个随机字符串作为向Redis中保存验证码的key
        String key = "admin:login:"+ UUID.randomUUID().toString().replaceAll("-", "");
        //将验证码保存到Redis中
        stringRedisTemplate.opsForValue().set(key,code,2, TimeUnit.MINUTES);
        //创建返回的对象
        CaptchaVo captchaVo = new CaptchaVo(imageUrl, key);
        return captchaVo;
    }

    @Override
    public String login(LoginVo loginVo) {
        //获取请求数据
        String username = loginVo.getUsername();
        String password = loginVo.getPassword();
        String captchaCode = loginVo.getCaptchaCode();
        String captchaKey = loginVo.getCaptchaKey();
        //验空
        if(StringUtils.isEmpty(username) || !StringUtils.hasLength(password) || !StringUtils.hasLength(captchaCode) || !StringUtils.hasLength(captchaKey)){
            //数据为空
            throw new LeaseException(ResultCodeEnum.DATA_ERROR);
        }
        //获取Redis中保存的验证码
        String redisCode = stringRedisTemplate.opsForValue().get(captchaKey);
        if(redisCode == null){
            //验证码已过期
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        //判断验证码是否正确
        if(!captchaCode.equalsIgnoreCase(redisCode)){
            //验证码不正确
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //验证验证码之后将Redis中的验证码删除
//        stringRedisTemplate.delete(captchaKey);
        //根据用户名查询数据库获取SysUser对象
        SystemUser systemUser = systemUserMapper.selectOne(new LambdaQueryWrapper<SystemUser>().eq(SystemUser::getUsername, username));
        if(systemUser == null){
            //用户名不存在
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }
        //将用户输入的明文的密码进行MD5加密后与SysUser中的密码进行比较
        if(!DigestUtils.md5DigestAsHex(password.getBytes()).equals(systemUser.getPassword())){
            //密码不正确
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //判断用户是否被禁用
        if(systemUser.getStatus().getCode()== 0){
            //账号被禁用
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        //使用JwtUtil工具类生成Token
        String token = JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());
        return token;
    }

    @Override
    public SystemUserInfoVo getSysUserInfoVoByUserId(Long userId) {
        SystemUser systemUser = systemUserMapper.selectById(userId);
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }
}
